/*
 * 文件名： ScoreShopDetailZero.java
 * 描    述：积分商城--0元兑换详细界面
 * 时    间：2015-3-25 下午5:47:21
 * 版    本：V1.0
 */

package com.miguo.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.miguo.activity.base.BaseActivity;
import com.miguo.app.AppContext;
import com.miguo.app.AppHelper;
import com.miguo.bean.ChouJiangGoodsBean;
import com.miguo.framework.request.JsonData;
import com.miguo.framework.utils.Toast;
import com.miguo.framework.view.dialogs.fragment.SimpleDialogFragment;
import com.miguo.framework.view.dialogs.iface.ISimpleDialogListener;
import com.miguo.http.HttpClient;
import com.miguo.http.Url;
import com.miguo.http.callback.AjaxCallBack;
import com.miguo.ui.R;
import com.miguo.utils.StringUtils;
import com.miguo.view.TimeTextView;
import com.mrper.util.DeviceUtil;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.HashMap;
import java.util.Map;

public class ScoreShopDetailExchangeActivity extends BaseActivity implements
        OnClickListener, ISimpleDialogListener {

    private int exchangeScore;
    private TimeTextView time;
    private RelativeLayout mAddressRl;
    private TextView mAccountEmpty, mAccountName, mAccountAddress, mAccountPhone;
    private String id = null;

    private static final int REQUEST_SIMPLE_TIPS = 1;
    private static final int REQUEST_SIMPLE_ADDRESS = 2;
    private static final int REQUEST_SIMPLE_SCORE = 3;
    private static final int REQUEST_SIMPLE_SCCEED = 4;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score_shop_detail_exchange);
        initView();
    }

    private void initView() {
        ChouJiangGoodsBean bean = (ChouJiangGoodsBean) getIntent()
                .getSerializableExtra("bean");
        // 商品id
        id = bean.id;

        ScrollView scroll = (ScrollView) findViewById(R.id.score_shop_exchange_scroll);
        if (Build.VERSION.SDK_INT >= 9) {
            scroll.setOverScrollMode(View.OVER_SCROLL_NEVER);
        }
        // 剩余时间
        time = (TimeTextView) findViewById(R.id.score_shop_exchange_time);
        time.setTime(Long.parseLong(bean.endTime));
        time.run();

        // 图片
        //设置图片容器尺寸
        View imageContaienrView = findViewById(R.id.score_shop_exchange_rl);
        LinearLayout.LayoutParams containerLayoutParams = (LinearLayout.LayoutParams)imageContaienrView.getLayoutParams();
        containerLayoutParams.height = DeviceUtil.getScreenWidth(mContext);
        imageContaienrView.setLayoutParams(containerLayoutParams);

        ImageView imageView = (ImageView) findViewById(R.id.score_shop_exchange_img);
        ViewGroup.LayoutParams imgLayoutParams = imageView.getLayoutParams();
        imgLayoutParams.height = containerLayoutParams.height;
        imageView.setLayoutParams(imgLayoutParams);
        ImageLoader.getInstance().displayImage(bean.img, imageView);
        // 描述
        TextView name = (TextView) findViewById(R.id.score_shop_exchange_title_tv);
        name.setText(bean.name);
        // 库存
        TextView count = (TextView) findViewById(R.id.score_shop_exchange_stock_tv);
        count.setText(bean.count + "人已兑换(当前库存" + bean.stock + "件)");

        // 积分
        TextView score = (TextView) findViewById(R.id.score_shop_exchange_score_tv);
        String src = bean.integral + "积分\t\t￥" + bean.price;
        SpannableString sb = new SpannableString(src);
        // 设置字体
        sb.setSpan(new AbsoluteSizeSpan(12, true), src.indexOf("￥"),
                src.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置颜色
        sb.setSpan(new ForegroundColorSpan(0xff666666), src.indexOf("￥"),
                src.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置删除线
        sb.setSpan(new StrikethroughSpan(), src.indexOf("￥"), src.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        score.setText(sb);

        exchangeScore = Integer.parseInt(bean.integral);


        // 编辑地址
        mAddressRl = (RelativeLayout) findViewById(R.id.score_shop_exchange_address_rl);
        mAddressRl.setOnClickListener(this);
        // 收货地址信息

        mAccountEmpty = (TextView) findViewById(R.id.score_shop_exchange_address_empty);
        mAccountName = (TextView) findViewById(R.id.score_shop_exchange_name_tv);
        mAccountPhone = (TextView) findViewById(R.id.score_shop_exchange_phone_tv);
        mAccountAddress = (TextView) findViewById(R.id.score_shop_exchange_address_tv);
        writeAddress();

        // 兑换
        findViewById(R.id.score_shop_exchange_btn).setOnClickListener(this);

        // 兑换规则
        TextView rule = (TextView) findViewById(R.id.score_shop_exchange_rule_tv);
        rule.setText(Html.fromHtml(this.getResources().getString(
                R.string.score_shop_exchange_rule)));
        //兑换事项
        TextView matter = (TextView) findViewById(R.id.score_shop_exchange_matter_tv);
        matter.setText(Html.fromHtml(this.getResources().getString(
                R.string.score_shop_exchange_matter)));
    }

    // 填写收货地址
    private void writeAddress() {
        if (AppContext.UserInfo().getIsLogin()) {
            if (TextUtils.isEmpty(AppContext.UserInfo().getTruename())) {
                mAccountEmpty.setText("请点击设置兑换地址");
            } else {
                mAccountEmpty.setText("");
                mAccountName.setText(AppContext.UserInfo().getTruename());
                mAccountPhone.setText(AppContext.UserInfo().getTelePhone());
                mAccountAddress.setText(AppContext.UserInfo().getArea() + AppContext.UserInfo().getAddress());
            }
            mAddressRl.setVisibility(View.VISIBLE);
        } else {
            mAddressRl.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 抽奖
            case R.id.score_shop_exchange_btn:
                // 登录
                if (AppContext.UserInfo().getIsLogin()) {
                    // 积分不足
                    if (StringUtils.StrToInt(AppContext.UserInfo().getScore()) - exchangeScore < 0) {
                        showNoEnoughScoreDialog();
                        return;
                    } else if (time.isOver()) {
                        Toast.show(mContext, "改活动已经结束");
                        return;
                    } else if (!isAddressInfo()) {
                        showNoAddressDialog();
                    } else if (isAddressInfo()) {
                        showTipsDialog();
                    }
                } else {// 未登录
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.score_shop_exchange_address_rl:
                // 修改地址
                if (AppContext.UserInfo().getIsLogin()) {
                    startActivity(new Intent(this, AcceptAddressActivity.class));
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
        }

    }

    private boolean isAddressInfo() {
        if (StringUtils.isEmpty(AppContext.UserInfo().getTruename())) {
            Toast.show(mContext, "请点击修改填写收货人姓名");
            return false;
        }
        if (StringUtils.isEmpty(AppContext.UserInfo().getArea())) {
            Toast.show(mContext, "请点击修改填写收货地址");
            return false;
        }
        if (!StringUtils.isPhoneNumber(AppContext.UserInfo().getTelePhone())) {
            Toast.show(mContext, "请点击修改填写手机号码");
            return false;
        }
        return true;
    }

    // 显示提示抽奖对话框
    private void showTipsDialog() {
        SimpleDialogFragment.createBuilder(this, getSupportFragmentManager())
                .setCancelableOnTouchOutside(false)
                .setTitle(R.string.dialog_tips)
                .setMessage("兑换改商品将减少" + exchangeScore + "积分")
                .setNegativeButtonText(R.string.dialog_cancle)
                .setPositiveButtonText("确认参与")
                .setRequestCode(REQUEST_SIMPLE_TIPS)
                .show();
    }

    // 积分不足dialog
    private void showNoEnoughScoreDialog() {
        SimpleDialogFragment.createBuilder(this, getSupportFragmentManager())
                .setCancelableOnTouchOutside(false)
                .setTitle(R.string.dialog_tips)
                .setMessage(R.string.dialog_score_shop_no_enough_score)
                .setNegativeButtonText(R.string.dialog_cancle)
                .setPositiveButtonText(R.string.dialog_sign_in)
                .setRequestCode(REQUEST_SIMPLE_SCORE)
                .show();
    }

    // 没有填写收货信息对话框
    private void showNoAddressDialog() {
        SimpleDialogFragment.createBuilder(this, getSupportFragmentManager())
                .setCancelableOnTouchOutside(false)
                .setTitle(R.string.dialog_tips)
                .setMessage(R.string.dialog_score_shop_no_address)
                .setNegativeButtonText(R.string.dialog_cancle)
                .setPositiveButtonText(R.string.dialog_score_shop_setting_now)
                .setRequestCode(REQUEST_SIMPLE_ADDRESS)
                .show();
    }

    // 兑换成功对话框
    private void showSucceedDialog() {
        SimpleDialogFragment.createBuilder(this, getSupportFragmentManager())
                .setCancelableOnTouchOutside(false)
                .setTitle(R.string.dialog_tips)
                .setMessage(R.string.dialog_score_shop_exchange_succeed_text)
                .setPositiveButtonText(R.string.dialog_ok)
                .setRequestCode(REQUEST_SIMPLE_SCCEED)
                .show();
    }

    private void duiHuan() {
        AjaxCallBack handler = new AjaxCallBack(mActivity, "正在兑换中...") {
            @Override
            public void onRequestFinish(JsonData json) {
                super.onRequestFinish(json);
                if (json.optInt("status") == 200) {
                    // 兑换成功
                    showSucceedDialog();
                } else {
                    if (json.optInt("status") == 401) {
                        writeAddress();
                    }
                    Toast.show(mContext, json.optString("info"));
                }
            }
        };

        Map<String, String> param = new HashMap<String, String>();
        param.put("id", id);
        param.put("token", AppContext.UserInfo().getToken());
        HttpClient.postEncryptData(Url.toRoute(Url.Exchange.Confirmorder, 1), param,
                handler);
    }

    @Override
    protected void onDestroy() {
        time = null;
        super.onDestroy();
    }

    @Override
    public void onNegativeButtonClicked(int requestCode) {
    }

    @Override
    public void onNeutralButtonClicked(int requestCode) {
    }

    @Override
    public void onPositiveButtonClicked(int requestCode) {
        switch (requestCode) {
            case REQUEST_SIMPLE_TIPS:
                duiHuan();
                break;
            case REQUEST_SIMPLE_SCORE:
                AppHelper.StartSign(this);
                break;
            case REQUEST_SIMPLE_SCCEED:
                break;
            case REQUEST_SIMPLE_ADDRESS:
                if (AppContext.UserInfo().getIsLogin()) {
                    startActivity(new Intent(this, AcceptAddressActivity.class));
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        writeAddress();
    }
}
